package com.ruoyi.system.service.impl;

import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.system.service.ISmsService;
import com.ruoyi.system.service.ITencentSmsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 短信服务Service业务层处理
 *
 * @author 大根教会
 * @date 2025-07-27
 */
@Service
public class SmsServiceImpl implements ISmsService {

    private static final Logger log = LoggerFactory.getLogger(SmsServiceImpl.class);

    @Autowired
    private ITencentSmsService tencentSmsService;

    @Autowired
    private RedisCache redisCache;

    /**
     * 短信验证码长度
     */
    @Value(value = "${sms.codeLength}")
    private int codeLength;

    /**
     * 短信验证码过期时间，单位分钟
     */
    @Value(value = "${sms.expireMinutes}")
    private int expireMinutes;

    /**
     * 不能重复发送时间间隔，单位秒
     */
    @Value(value = "${sms.frequencyLimit}")
    private int frequencyLimit;

    @Override
    public void sendVerificationCode(String mobile) {
        //检查发送频率
        String redisKeyFrequency = CacheConstants.SMS_FREQUENCY_KEY + mobile;
        if (redisCache.hasKey(redisKeyFrequency)) {
            throw new RuntimeException("请求过于频繁，请稍后再试");
        }
        //生成随机验证码
        String code = generateRandomCode(codeLength);
        log.info("手机号：{}，短信验证码：{}", mobile, code);
        //发送短信验证码
        //tencentSmsService.sendSms(mobile, code, expireMinutes);
        //短信验证码存储到缓存并设置过期时间
        String redisKey = CacheConstants.SMS_CODE_KEY + mobile;
        redisCache.setCacheObject(redisKey, code, expireMinutes, TimeUnit.MINUTES);
        //设置频率限制到缓存并设置过期时间
        redisCache.setCacheObject(redisKeyFrequency, 1, frequencyLimit, TimeUnit.SECONDS);
    }

    @Override
    public boolean verifyCode(String mobile, String code) {
        String redisKey = CacheConstants.SMS_CODE_KEY + mobile;
        String storedCode = redisCache.getCacheObject(redisKey);

        if (storedCode != null && storedCode.equals(code)) {
            //删除验证码
            redisCache.deleteObject(redisKey);
            return true;
        }

        return false;
    }

    /**
     * 生成随机验证码
     * @param length
     * @return
     */
    private String generateRandomCode(int length) {
        Random random = new Random();
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < length; i++) {
            code.append(random.nextInt(10));
        }
        return code.toString();
    }
}
